/************************************************************************************
 *  Copyright 2013 WZITech Corporation. All rights reserved.
 *	
 *	模	块：		AuthenticationInterceptor
 *	包	名：		com.wzitech.gamegold.facade.frontend.interceptor
 *	项目名称：	gamegold-facade-frontend
 *	作	者：		SunChengfei
 *	创建时间：	2014-1-13
 *	描	述：		
 *	更新纪录：	1. SunChengfei 创建于 2014-1-13 下午5:59:36
 * 				
 ************************************************************************************/
package com.hn658.groupshare.frontend.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.springframework.beans.factory.annotation.Autowired;

import com.hn658.framework.common.interceptor.AbstractInterceptor;
import com.hn658.framework.logging.Logger;
import com.hn658.framework.logging.LoggerFactory;
import com.hn658.framework.logging.enums.LogCategory;
import com.hn658.framework.shared.context.RequestContext;
import com.hn658.groupshare.common.expection.FilterException;
import com.hn658.groupshare.common.validate.IValidateIpManager;

/**
 * @author ztjie
 */
public class ValidateIpInterceptor extends AbstractInterceptor {
	/**
	 * 日志输出
	 */
	private static final Logger logger = LoggerFactory.getLogger(ValidateIpInterceptor.class);
	
	@Autowired
	private IValidateIpManager validateIpManager;
	
	/**
	 * @param phase
	 */
	public ValidateIpInterceptor() {
		super(Phase.RECEIVE);
	}

	@Override
	public void handle(Message message) {
		// 获取当前的http请求
		HttpServletRequest request = (HttpServletRequest) message
				.get(AbstractHTTPDestination.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) message
				.get(AbstractHTTPDestination.HTTP_RESPONSE);
		// 设置当前请求上下文信息
		this.initRequestContext(message, request, response);
		
		String ip = RequestContext.getCurrentContext().getIp();
		if(StringUtils.isNotBlank(ip)){
			logger.debug(LogCategory.SYSTEM, "当前拦截的IP为 {}", ip);
			//如果IP是白名单内的,就可能进行操作,如果不是不能进行操作
			if(!validateIpManager.validate(ip)){
				throw new FilterException(FilterException.ValidateIpError);
			}
		}
	}
}
